package cn.ug.service.impl;

import cn.ug.bean.LoginBean;
import cn.ug.bean.type.OnlineType;
import cn.ug.service.LoginCacheService;
import cn.ug.service.LoginInfoService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import java.util.concurrent.TimeUnit;

import static cn.ug.util.ConstantUtil.COLON;

@Service
public class LoginInfoServiceImpl extends BaseServiceImpl implements LoginInfoService {
	protected static final String TYPE_NAME = LoginInfoServiceImpl.class.getTypeName();
    protected static final String KEY_ID    = "LOGIN:ID:";
    protected static final String KEY_OBJ   = "LOGIN:OBJ:";
    protected static final String KEY_PLATFORM   = "LOGIN:PLATFORM:";
	@Autowired
	protected LoginCacheService loginCacheService;

	@Override
	public LoginBean get(String key) {
		return get(key, false);
	}

	protected LoginBean get(String key, boolean refresh) {

		Object obj = loginCacheService.getCache(TYPE_NAME, key);
		if(null == obj || !(obj instanceof String)) {
			return null;
		}
		String id = (String) obj;

		Object platformObj = loginCacheService.getCache(TYPE_NAME, KEY_PLATFORM + key);
		if (null == platformObj || !(platformObj instanceof String)) {
			return null;
		}
		String platform = (String)platformObj;

		// 根据ID查找最新accessToken
		obj = loginCacheService.getCache(TYPE_NAME, KEY_ID + platform + COLON + id);
		if(null == obj || !(obj instanceof String)) {
			return null;
		}

		// 根据ID查找最新Bean
		String accessToken = (String) obj;
		obj = loginCacheService.getCache(TYPE_NAME, KEY_OBJ + platform + COLON + id);
		if(null == obj || !(obj instanceof LoginBean)) {
			return null;
		}

		LoginBean loginBean = (LoginBean) obj;
		if(!StringUtils.equals(key, accessToken)){
			// 如果不是最后登录，则视为离线
			loginBean.setOnlineType(OnlineType.OFFLINE);
			return loginBean;
		}

		return loginBean;
	}
}

